package uk.ac.ebi.bioinvindex.dao.ejb3;

import org.hibernate.Session;

import javax.persistence.EntityManager;

/**
 * User: Nataliya Sklyar (nsklyar@ebi.ac.uk)
 * Date: Sep 20, 2007
 */
public abstract class AbstractEJB3DAO {

	protected EntityManager entityManager;

	protected AbstractEJB3DAO() {
	}

	protected AbstractEJB3DAO(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@SuppressWarnings("unchecked")
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}


	protected Session getSession() {
		if (entityManager == null) {
			throw new IllegalStateException("EntityManager has not been set on DAO before usage");
		}

		if (!(entityManager.getDelegate() instanceof Session)) {
			throw new IllegalStateException("EntityManager doesn't have hibernate session");
		}
		return (Session) entityManager.getDelegate();
	}
}